﻿using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using YJTShiftManagement.Events;
using YJTShiftManagement.Models;
using YJTShiftManagement.Service;

namespace YJTShiftManagement
{
    public partial class RecordDetails : UIForm
    {
        private string docid = null;
        private string date = null;
        private sch_records doc_Check_s;
        // 记录初始控件位置和大小
        private Rectangle originalFormSize;
        private Dictionary<Control, Rectangle> controlPositions = new Dictionary<Control, Rectangle>();

        public RecordDetails(string docid, string date)
        {
            InitializeComponent();
            dateTimePicker2.DateFormat = "HH:mm";
            dateTimePicker1.DateFormat = "HH:mm";
            // 设置所有单元格内容居中
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            // 设置表头文字居中
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            // 设置时间为 00:00

            dateTimePicker2.Value = DateTime.Today.AddHours(23).AddMinutes(59);

            dataGridView1.RowHeadersVisible = false;
            dataGridView1.EnableHeadersVisualStyles = false; // 禁用默认样式
            dataGridView1.CellPainting += DataGridView1_CellPainting;
            dataGridView1.CellMouseUp += DataGridView1_CellMouseUp;
            dataGridView1.CellValueChanged += DataGridView1_CellValueChanged;
            dataGridView1.CellMouseClick += DataGridViewEmail_CellMouseClick;
            uiComboTreeView1.TreeView.AfterCheck += TreeView_AfterCheck;
            checkBox1.Visible = false;
            this.Load += (s, e) =>
            {
                originalFormSize = new Rectangle(0, 0, this.Width, this.Height);
                foreach (Control control in this.Controls)
                {
                    controlPositions.Add(control, new Rectangle(
                        control.Left, control.Top,
                        control.Width, control.Height
                    ));
                }
            };
            this.Resize += MainForm_Resize;
            doc_Check_s = new sch_records();
            this.docid = docid;
            this.date = date;
            Init(docid, date);
        }
        List<doc_check_amount> Vs = new List<doc_check_amount>();
        private void TreeView_AfterCheck(object sender, TreeViewEventArgs e)
        {
            // 1. 临时解除事件绑定
            uiComboTreeView1.TreeView.AfterCheck -= TreeView_AfterCheck;
            try
            {
                // 2. 安全类型转换
                if (!(e.Node.Tag is doc_check_amount docItem))
                {
                    e.Node.Checked = false;
                    return;
                }

                // 3. 检查唯一性
                string sign = docItem.ghzd_sign;
                if (Vs.Any(x => x.ghzd_sign == sign))
                {
                    e.Node.Checked = false; // ⚠️ 此处修改 Checked 不会触发事件
                }

                // 4. 更新集合
                if (e.Node.Checked)
                {
                    Vs.Add(docItem);
                }
                else
                {
                    Vs.Remove(docItem);
                }
            }
            finally
            {

                // 5. 重新绑定事件
                uiComboTreeView1.TreeView.AfterCheck += TreeView_AfterCheck;
            }
            List<doc_check_amount> data = new List<doc_check_amount>();
            uiComboTreeView1.Text = "";
            foreach (var item in Vs)
            {
                uiComboTreeView1.Text += $"{item.kind_name}({item.ghzd_sign}),";
                var request = new { ghzd_list = new string[] { item.his_sys_ghzd_id } };
                var result = BaseService.HttpService("api_back/api_scheduling/show_set_by_ghzd", request);
                if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                {
                }
                else
                {
                    this.ShowErrorDialog(result.msg);
                    if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                    return;
                }
            }
            var datas = Vs.Where(s => s.ghzd_sign == "图文").ToList();
            if (datas != null && datas.Count > 0)
            {
                checkBox1.Visible = true;
            }
            else
            {
                checkBox1.Checked = false;
                checkBox1.Visible = false;
            }
            doc_Check_Amounts = Vs;
        }
        private void MainForm_Resize(object sender, EventArgs e)
        {
            float widthRatio = (float)this.Width / originalFormSize.Width;
            float heightRatio = (float)this.Height / originalFormSize.Height;

            foreach (var entry in controlPositions)
            {
                Control control = entry.Key;
                Rectangle original = entry.Value;

                int newX = (int)(original.X * widthRatio);
                int newY = (int)(original.Y * heightRatio);
                int newWidth = (int)(original.Width * widthRatio);
                int newHeight = (int)(original.Height * heightRatio);

                control.Location = new Point(newX, newY);
                control.Size = new Size(newWidth, newHeight);
            }
        }
        private void Init(string doc_id, string date)
        {
            dataGridView1.Rows.Clear();

            var check_kind_request = new { doc_id = doc_id, is_internet = "yes" };
            var check_kind_result = BaseService.HttpService("api_back/api_scheduling/init_doc_all_check_kind", check_kind_request);
            if (check_kind_result.status == "success" && null != check_kind_result.data && false == string.IsNullOrEmpty(check_kind_result.data.ToString()))
            {
            }
            else
            {
                this.ShowErrorDialog(check_kind_result.msg);
                if (check_kind_result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                return;
            }
            var sch_detail_request = new { date = date, doc_id = doc_id };
            var sch_detail_result = BaseService.HttpService("api_back/api_scheduling/init_internet_doc_sch_detail", sch_detail_request);
            if (sch_detail_result.status == "success" && null != sch_detail_result.data && false == string.IsNullOrEmpty(sch_detail_result.data.ToString()))
            {
            }
            else
            {
                this.ShowErrorDialog(sch_detail_result.msg);
                if (sch_detail_result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                return;
            }
            doc_Check_s = JsonConvert.DeserializeObject<sch_records>(sch_detail_result.data.ToString());

            var cdata = JsonConvert.DeserializeObject<List<doc_check_amount>>(check_kind_result.data.ToString());
            if (doc_Check_s != null)
            {
                this.Doc_Name.Text = doc_Check_s.doc_name;
                this.Doc_Date.Text = $"{date}{doc_Check_s.week_chinese}";
                int i = 1;
                foreach (var item in doc_Check_s.sch_records_arr)
                {

                    int rowIndex = dataGridView1.Rows.Add();
                    DataGridViewRow row = dataGridView1.Rows[rowIndex];
                    string str = "";
                    if (item.skip == "1")
                        str = "跳过图文过程";
                    if (!string.IsNullOrEmpty(item.cancel_reason))
                    {
                        str += $"取消原因 ：{item.cancel_reason}";
                    }
                    // 填充数据

                    row.Cells["CheckBoxColumn"].Value = false;
                    row.Cells["serialNumber"].Value = i;
                    row.Cells["registrationType"].Value = item.kind_name;
                    row.Cells["check_amount"].Value = item.check_amount;
                    row.Cells["consultationHours"].Value = item.check_time;
                    row.Cells["shiftInstructions"].Value = item.transfer_reason;
                    row.Cells["remark"].Value = str;
                    i++;
                    if (item.status == "2")
                    {
                        dataGridView1.Rows[rowIndex].ReadOnly = true;
                        dataGridView1.Rows[rowIndex].Selected = false;
                        dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = Color.Gray;
                        dataGridView1.Rows[rowIndex].DefaultCellStyle.ForeColor = Color.LightGray;
                    }
                }
            }

            if (cdata != null)
            {
                foreach (var item in cdata)
                {
                    TreeNode node = new TreeNode($"{item.kind_name}({item.ghzd_sign})");
                    node.Tag = item; // 将整个对象存入 Tag
                    uiComboTreeView1.TreeView.Nodes.Add(node);
                }
            }
            dataGridView1.ClearSelection();    // 取消所有选中项

        }
        private void DataGridViewEmail_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;//当前鼠标在当前单元格中的坐标
                if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex];

                    string registrationType = currentRow.Cells["registrationType"].Value?.ToString();      // 安全获取值
                    string consultationHours = currentRow.Cells["consultationHours"].Value?.ToString();
                    string check_amount = currentRow.Cells["check_amount"].Value?.ToString();
                    Graphics g = this.dataGridView1.CreateGraphics();
                    string button2Text = "挂起";
                    var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                        s.check_time == consultationHours &&
                                                                        s.check_amount == check_amount);
                    if (data != null)
                    {
                        button2Text = data?.status == "1" ? "取消挂起" : "挂起"; // 根据状态字段动态命名
                        if (data?.status == "2")
                        {
                            return;
                        }

                    }
                    System.Drawing.Font myFont = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, 134);
                    SizeF sizeDel = g.MeasureString("删除", myFont);
                    SizeF sizeMod = g.MeasureString(button2Text, myFont);
                    SizeF sizeLook = g.MeasureString("取消", myFont);
                    float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width + sizeLook.Width);
                    float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width + sizeLook.Width);
                    float fLook = sizeLook.Width / (sizeDel.Width + sizeMod.Width + sizeLook.Width);

                    Rectangle rectTotal = new Rectangle(0, 0, this.dataGridView1.Columns[e.ColumnIndex].Width, this.dataGridView1.Rows[e.RowIndex].Height);
                    RectangleF rectDel = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * fDel, rectTotal.Height);
                    RectangleF rectMod = new RectangleF(rectDel.Right, rectTotal.Top, rectTotal.Width * fMod, rectTotal.Height);
                    RectangleF rectLook = new RectangleF(rectMod.Right, rectTotal.Top, rectTotal.Width * fLook, rectTotal.Height);
                    //判断当前鼠标在哪个“按钮”范围内

                    if (rectDel.Contains(curPosition))//删除
                        ShiftManagementButtonClick("删除", currentRow);
                    else if (rectMod.Contains(curPosition))//修改
                        ShiftManagementButtonClick(button2Text, currentRow);
                    else if (rectLook.Contains(curPosition))//查看
                        ShiftManagementButtonClick("取消", currentRow);
                }
            }
        }
        private string InputMessageBox(string title, string msg)
        {
            using (var inputDialog = new InputDialog(title, msg))
            {
                if (inputDialog.ShowDialog() == DialogResult.OK)
                {
                    if (inputDialog.IsConfirmed)
                    {
                        string userInput = inputDialog.InputText;
                        return userInput;
                    }
                }
                else
                {
                    return null;
                }
            }
            return null;
        }
        private void ShiftManagementButtonClick(string str, DataGridViewRow currentRow)
        {


            string registrationType = currentRow.Cells["registrationType"].Value?.ToString();      // 安全获取值
            string consultationHours = currentRow.Cells["consultationHours"].Value?.ToString();
            string check_amount = currentRow.Cells["check_amount"].Value?.ToString();
            var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                        s.check_time == consultationHours &&
                                                                        s.check_amount == check_amount);
            switch (str)
            {
                case "删除":
                    if (this.ShowAskDialog2($"消息内容：已填写排班信息，确定删除当前排班?", true))
                    {

                    }
                    else
                    {
                        return;
                    }
                    if (!string.IsNullOrEmpty(check_amount) && !string.IsNullOrEmpty(consultationHours) && !string.IsNullOrEmpty(registrationType))
                    {

                        if (data != null)
                        {
                            var request = new { internet_sch_record_id = data.internet_sch_record_id, is_delete = 1 };
                            var result = BaseService.HttpService("api_back/api_scheduling/edit_internet_doc_sch_record", request);

                            if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                            {
                                this.ShowSuccessDialog("删除成功！");
                                Init(docid, date);
                                return;
                            }
                            else
                            {
                                this.ShowErrorDialog(result.msg);
                                if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                                return;
                            }

                        }
                    }

                    break;
                case "挂起":
                    if (this.ShowAskDialog2($"消息内容：挂起后该时段将无法预约和挂号？", true))
                    {

                    }
                    else
                    {
                        return;
                    }
                    var msg = InputMessageBox("挂起原因", "请输入文本：");
                    if (msg == null) return;
                    if (!string.IsNullOrEmpty(check_amount) && !string.IsNullOrEmpty(consultationHours) && !string.IsNullOrEmpty(registrationType))
                    {

                        if (data != null)
                        {
                            var request = new { internet_sch_record_id = data.internet_sch_record_id, status = 1, suspend_reason = msg };
                            var result = BaseService.HttpService("api_back/api_scheduling/edit_internet_doc_sch_record", request);

                            if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                            {
                                this.ShowSuccessDialog("挂起成功！");
                                Init(docid, date);
                                return;
                            }
                            else
                            {
                                this.ShowErrorDialog(result.msg);
                                if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                                return;
                            }

                        }
                    }
                    break;
                case "取消":
                    if (this.ShowAskDialog2($"消息内容：是否将要取消排班？", true))
                    {

                    }
                    else
                    {
                        return;
                    }
                    var Cmsg = InputMessageBox("取消原因", "请输入文本："); if (Cmsg == null) return;
                    if (!string.IsNullOrEmpty(check_amount) && !string.IsNullOrEmpty(consultationHours) && !string.IsNullOrEmpty(registrationType))
                    {
                        if (data != null)
                        {
                            var request = new { internet_sch_record_id = data.internet_sch_record_id, status = 2, cancel_reason = Cmsg };
                            var result = BaseService.HttpService("api_back/api_scheduling/edit_internet_doc_sch_record", request);

                            if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                            {
                                this.ShowSuccessDialog("取消排班成功！");
                                Init(docid, date);
                                return;
                            }
                            else
                            {
                                this.ShowErrorDialog(result.msg);
                                if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                                return;
                            }

                        }
                    }
                    break;
                case "取消挂起":
                    if (this.ShowAskDialog2($"消息内容：是否将要取消挂起？", true))
                    {

                    }
                    else
                    {
                        return;
                    }
                    if (!string.IsNullOrEmpty(check_amount) && !string.IsNullOrEmpty(consultationHours) && !string.IsNullOrEmpty(registrationType))
                    {
                        if (data != null)
                        {
                            var request = new { internet_sch_record_id = data.internet_sch_record_id, status = 0, suspend_reason = "" };
                            var result = BaseService.HttpService("api_back/api_scheduling/edit_internet_doc_sch_record", request);

                            if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                            {
                                this.ShowSuccessDialog("取消挂起成功！");
                                Init(docid, date);
                                return;
                            }
                            else
                            {
                                this.ShowErrorDialog(result.msg);
                                if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                                return;
                            }

                        }
                    }
                    break;
            }
        }
        // 绘制列头复选框
        private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == dataGridView1.Columns["CheckBoxColumn"].Index)
            {
                e.PaintBackground(e.CellBounds, true);
                e.PaintContent(e.CellBounds);

                // 计算复选框位置（考虑水平滚动偏移）
                int xOffset = dataGridView1.HorizontalScrollingOffset;
                Rectangle colRect = dataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, true);

                int x = e.CellBounds.Left + (e.CellBounds.Width - 15) / 2;
                int y = e.CellBounds.Top + (e.CellBounds.Height - 15) / 2;
                Rectangle checkRect = new Rectangle(x, y, 15, 15);

                // 确定复选框状态
                CheckBoxState state = IsAllChecked() ? CheckBoxState.CheckedNormal :
                    (IsAnyChecked() ? CheckBoxState.MixedNormal : CheckBoxState.UncheckedNormal);

                CheckBoxRenderer.DrawCheckBox(e.Graphics, checkRect.Location, state);

                e.Handled = true;
            }
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {

                if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    // 获取当前行数据对象（假设绑定的是自定义类）
                    DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex];
                    string registrationType = currentRow.Cells["registrationType"].Value?.ToString();      // 安全获取值
                    string consultationHours = currentRow.Cells["consultationHours"].Value?.ToString();
                    string check_amount = currentRow.Cells["check_amount"].Value?.ToString();
                    // 根据行数据生成按钮名称（示例逻辑）
                    string button1Text = "删除"; // 默认名称
                    string button3Text = "取消";
                    string button2Text = "挂起";
                    var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                       s.check_time == consultationHours &&
                                                                       s.check_amount == check_amount);

                    if (data != null)
                    {
                        button2Text = data?.status == "1" ? "取消挂起" : "挂起"; // 根据状态字段动态命名
                    }

                    // 设置绘制格式
                    StringFormat sf = new StringFormat
                    {
                        Alignment = StringAlignment.Center,
                        LineAlignment = StringAlignment.Center,
                        Trimming = StringTrimming.EllipsisCharacter
                    };

                    e.PaintBackground(e.CellBounds, false);

                    // 设置字体
                    using (Font myFont = new Font("微软雅黑", 9F, FontStyle.Underline))
                    {
                        // 测量文本宽度
                        SizeF sizeDel = e.Graphics.MeasureString(button1Text, myFont);
                        SizeF sizeMod = e.Graphics.MeasureString(button2Text, myFont);
                        SizeF sizeLook = e.Graphics.MeasureString(button3Text, myFont);

                        // 计算比例
                        float totalWidth = sizeDel.Width + sizeMod.Width + sizeLook.Width;
                        float fDel = sizeDel.Width / totalWidth;
                        float fMod = sizeMod.Width / totalWidth;
                        float fLook = sizeLook.Width / totalWidth;

                        // 定义按钮区域
                        RectangleF rectDel = new RectangleF(
                            e.CellBounds.Left,
                            e.CellBounds.Top,
                            e.CellBounds.Width * fDel,
                            e.CellBounds.Height
                        );

                        RectangleF rectMod = new RectangleF(
                            rectDel.Right,
                            e.CellBounds.Top,
                            e.CellBounds.Width * fMod,
                            e.CellBounds.Height
                        );

                        RectangleF rectLook = new RectangleF(
                            rectMod.Right,
                            e.CellBounds.Top,
                            e.CellBounds.Width * fLook,
                            e.CellBounds.Height
                        );

                        // 绘制按钮文本
                        e.Graphics.DrawString(button1Text, myFont, Brushes.Black, rectDel, sf);
                        e.Graphics.DrawString(button2Text, myFont, Brushes.Black, rectMod, sf);
                        e.Graphics.DrawString(button3Text, myFont, Brushes.Black, rectLook, sf);
                    }

                    e.Handled = true;
                }
            }
        }

        // 检查是否所有行都被选中
        private bool IsAllChecked(DataGridViewRow row)
        {

            if (row == null) return false;
            string registrationType = row.Cells["registrationType"].Value?.ToString();      // 安全获取值
            string consultationHours = row.Cells["consultationHours"].Value?.ToString();
            string check_amount = row.Cells["check_amount"].Value?.ToString();
            var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                        s.check_time == consultationHours &&
                                                                        s.check_amount == check_amount);
            if (data != null)
            {
                if (data.status == "2")
                {
                    return true;
                }
            }
            if (!Convert.ToBoolean(row.Cells["CheckBoxColumn"].Value))
                return false;
            return true;

        }
        private bool IsAllChecked()
        {
            if (dataGridView1.Rows.Count == 0) return false;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.IsNewRow) continue;
                if (!Convert.ToBoolean(row.Cells["CheckBoxColumn"].Value))
                    return false;
            }
            return true;
        }
        // 检查是否有任意行被选中
        private bool IsAnyChecked(DataGridViewRow row)
        {
            if (Convert.ToBoolean(row.Cells["CheckBoxColumn"].Value))
                return true;
            return false;
        }
        private bool IsAnyChecked()
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.IsNewRow) continue;
                if (Convert.ToBoolean(row.Cells["CheckBoxColumn"].Value))
                    return true;
            }
            return false;
        }
        private void DataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 点击列头复选框区域
            if (e.RowIndex == -1 && e.ColumnIndex == dataGridView1.Columns["CheckBoxColumn"].Index)
            {
                // 计算复选框点击区域
                int x = dataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, true).Width / 2 - 7;
                int y = dataGridView1.ColumnHeadersHeight / 2 - 7;
                Rectangle headerCheckBoxRect = new Rectangle(x, y, 15, 15);

                // 判断点击位置是否在复选框内
                if (headerCheckBoxRect.Contains(e.Location))
                {
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        bool newState = !IsAllChecked(row);
                        row.Cells["CheckBoxColumn"].Value = newState;
                    }
                    dataGridView1.EndEdit();
                    dataGridView1.Refresh(); // 刷新列头显示
                                             // 更高效的重绘方式[10](@ref)

                }
            }
        }
        private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Columns["CheckBoxColumn"].Index && e.RowIndex >= 0)
            {
                dataGridView1.InvalidateColumn(e.ColumnIndex); // 刷新列头
            }
        }

        private void SuspendButton_Click(object sender, EventArgs e)
        {
            if (!IsAnyChecked())
            {
                this.ShowErrorDialog($"消息内容：请勾选数据后在进行操作！");
                return;
            }
            if (this.ShowAskDialog2($"消息内容：是否批量挂起？", true))
            {

            }
            else
            {
                return;
            }
            var Cmsg = InputMessageBox("挂起原因", "请输入文本："); if (Cmsg == null) return;
            List<string> internet_sch_record_id_list = new List<string>();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                bool newState = IsAnyChecked(row);
                if (newState)
                {
                    string registrationType = row.Cells["registrationType"].Value?.ToString();      // 安全获取值
                    string consultationHours = row.Cells["consultationHours"].Value?.ToString();
                    string check_amount = row.Cells["check_amount"].Value?.ToString();
                    var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                                s.check_time == consultationHours &&
                                                                                s.check_amount == check_amount);
                    if (data == null) break;
                    internet_sch_record_id_list.Add(data.internet_sch_record_id);

                    if (internet_sch_record_id_list != null && internet_sch_record_id_list.Count > 0)
                    {
                        var request = new { action = "suspend", internet_sch_record_id_list = internet_sch_record_id_list.ToArray(), suspend_else_param = new { status = 1, suspend_reason = Cmsg } };
                        var result = BaseService.HttpService("api_back/api_scheduling/batchedit_internet_doc_sch_record", request);

                        if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                        {

                        }
                        else
                        {
                            this.ShowErrorDialog(result.msg);
                            if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                            return;
                        }
                    }
                }
            }
            this.ShowSuccessDialog("批量挂起成功！");
            Init(docid, date);
            return;

        }

        private void CancelSuspendButton_Click(object sender, EventArgs e)
        {
            if (!IsAnyChecked())
            {
                this.ShowErrorDialog($"消息内容：请勾选数据后在进行操作！");
                return;
            }
            if (this.ShowAskDialog2($"消息内容：是否批量取消挂起？", true))
            {

            }
            else
            {
                return;
            }
            List<string> internet_sch_record_id_list = new List<string>();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                bool newState = IsAnyChecked(row);
                if (newState)
                {
                    string registrationType = row.Cells["registrationType"].Value?.ToString();      // 安全获取值
                    string consultationHours = row.Cells["consultationHours"].Value?.ToString();
                    string check_amount = row.Cells["check_amount"].Value?.ToString();
                    var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                                s.check_time == consultationHours &&
                                                                                s.check_amount == check_amount);
                    if (data == null) break;
                    internet_sch_record_id_list.Add(data.internet_sch_record_id);

                    if (internet_sch_record_id_list != null && internet_sch_record_id_list.Count > 0)
                    {
                        var request = new { action = "suspend", internet_sch_record_id_list = internet_sch_record_id_list.ToArray(), suspend_else_param = new { status = 0, suspend_reason = "" } };
                        var result = BaseService.HttpService("api_back/api_scheduling/batchedit_internet_doc_sch_record", request);

                        if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                        {

                        }
                        else
                        {
                            this.ShowErrorDialog(result.msg);
                            if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                            return;
                        }
                    }
                }
            }
            this.ShowSuccessDialog("取消批量挂起成功！");
            Init(docid, date);
            return;
        }

        private void CancelShiftButton_Click(object sender, EventArgs e)
        {
            if (!IsAnyChecked())
            {
                this.ShowErrorDialog($"消息内容：请勾选数据后在进行操作！");
                return;
            }
            if (this.ShowAskDialog2($"消息内容：是否批量取消排班？", true))
            {

            }
            else
            {
                return;
            }
            var Cmsg = InputMessageBox("取消原因", "请输入文本："); if (Cmsg == null) return;

            List<string> internet_sch_record_id_list = new List<string>();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                bool newState = Convert.ToBoolean(row.Cells["CheckBoxColumn"].Value);
                if (newState)
                {
                    string registrationType = row.Cells["registrationType"].Value?.ToString();      // 安全获取值
                    string consultationHours = row.Cells["consultationHours"].Value?.ToString();
                    string check_amount = row.Cells["check_amount"].Value?.ToString();
                    var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                                s.check_time == consultationHours &&
                                                                                s.check_amount == check_amount);
                    if (data == null) break;
                    internet_sch_record_id_list.Add(data.internet_sch_record_id);

                    if (internet_sch_record_id_list != null && internet_sch_record_id_list.Count > 0)
                    {
                        var request = new { action = "cancel", internet_sch_record_id_list = internet_sch_record_id_list.ToArray(), cancel_else_param = new { cancel_reason = Cmsg } };
                        var result = BaseService.HttpService("api_back/api_scheduling/batchedit_internet_doc_sch_record", request);

                        if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                        {
                        }
                        else
                        {
                            this.ShowErrorDialog(result.msg);
                            if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                            return;
                        }

                    }
                }
            }
            this.ShowSuccessDialog("批量取消排班成功！");
            Init(docid, date);
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if (!IsAnyChecked())
            {
                this.ShowErrorDialog($"消息内容：请勾选数据后在进行操作！");
                return;
            }
            if (this.ShowAskDialog2($"消息内容：是否批量删除？", true))
            {

            }
            else
            {
                return;
            }
            List<string> internet_sch_record_id_list = new List<string>();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                bool newState = IsAnyChecked(row);
                if (newState)
                {
                    string registrationType = row.Cells["registrationType"].Value?.ToString();      // 安全获取值
                    string consultationHours = row.Cells["consultationHours"].Value?.ToString();
                    string check_amount = row.Cells["check_amount"].Value?.ToString();
                    var data = doc_Check_s.sch_records_arr.FirstOrDefault(s => s.kind_name == registrationType &&
                                                                                s.check_time == consultationHours &&
                                                                                s.check_amount == check_amount);
                    if (data == null) break;
                    internet_sch_record_id_list.Add(data.internet_sch_record_id);

                    if (internet_sch_record_id_list != null && internet_sch_record_id_list.Count > 0)
                    {
                        var request = new { action = "del", internet_sch_record_id_list = internet_sch_record_id_list.ToArray() };
                        var result = BaseService.HttpService("api_back/api_scheduling/batchedit_internet_doc_sch_record", request);

                        if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                        {

                        }
                        else
                        {
                            this.ShowErrorDialog(result.msg);
                            if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                            return;
                        }
                    }
                }
            }
            this.ShowSuccessDialog("批量删除成功！");
            Init(docid, date);
        }
        private List<doc_check_amount> doc_Check_Amounts = new List<doc_check_amount>();
        private void uiComboTreeView1_NodesSelected(object sender, TreeNodeCollection nodes)
        {

        }
        private bool isTW = false;
        private void AddButton_Click(object sender, EventArgs e)
        {
            if (Vs.Count == 0)
            {
                this.ShowErrorDialog("请选择挂号类型后在进行添加！");
                return;
            }
            List<string> dd = new List<string>();
            foreach (var item in doc_Check_Amounts)
            {
                dd.Add(item.his_sys_ghzd_id);
                if (item.ghzd_sign == "图文")
                {
                    isTW = true;
                }
            }
            var request = new
            {
                check_time = new string[] { dateTimePicker1.Value.ToString("HH:mm"), dateTimePicker2.Value.ToString("HH:mm") },
                date,
                doc_id = docid,
                ghzd_list = dd.ToArray(),
                ghzd_sign = isTW == true ? "图文" : "",
                partake = "0",
                skip = checkBox1.Checked ? 1 : 0
            };
            var result = BaseService.HttpService("api_back/api_scheduling/insert_internet_doc_sch_record", request);

            if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
            {
                this.ShowSuccessDialog("添加成功！");
                Init(docid, date);
                return;
            }
            else
            {
                this.ShowErrorDialog(result.msg);
                if (result.msg.Contains("认证失败")) { this.Hide(); EventManager.Instance.RaiseStringEvent("登录界面"); }
                return;
            }
        }
        private void BeginDate_ValueChanged(object sender, DateTime value)
        {

        }
        private void EndDate_ValueChanged(object sender, DateTime value)
        {

        }

        private void dateTimePicker1_ValueChanged(object sender, DateTime value)
        {

            if (dateTimePicker2.Value.TimeOfDay < dateTimePicker1.Value.TimeOfDay)
            {
                dateTimePicker1.Value = DateTime.Today; ;
            }
        }

        private void dateTimePicker2_ValueChanged(object sender, DateTime value)
        {
            if (dateTimePicker2.Value.TimeOfDay < dateTimePicker1.Value.TimeOfDay)
            {
                dateTimePicker2.Value = DateTime.Today.AddHours(23).AddMinutes(59); ;
            }
        }
    }
    public class DualDataItem
    {
        public string MainText { get; set; }  // 主显示文本（选中后展示）
        public string SubText { get; set; }   // 辅助文本（仅在下拉项中显示）
        public bool IsSelected { get; set; }  // 是否选中
    }
}
